package com.andy.qhb.game;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.entity.UsrGroups;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.websocket.MySocketSession;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

public class Global implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private static Logger logger = LoggerFactory.getLogger(Global.class);
	
	/**
	 * 在线人数
	 */
	public static AtomicInteger onlineNumber = new AtomicInteger();

	private static Map<Long,MySocketSession> sessionMap = Maps.newConcurrentMap();
	private static List<MySocketSession> sessions = Lists.newCopyOnWriteArrayList();
	
	public volatile static AtomicLong sysCurrHave ;
	
	public static void addSession(MySocketSession session){
		onlineNumber.incrementAndGet();
		sessions.add(session);
		
		if(logger.isInfoEnabled()){
			logger.info("有新连接加入！ 当前在线人数：{}，s={}", onlineNumber,sessions.size());
		}
	}
	
	public static void removeSession(MySocketSession session){
		if(sessions.remove(session)){
			onlineNumber.decrementAndGet();
		}
		GameUser user = session.getUser();
		if(user != null){
			sessionMap.remove(user.getId());
			session.removeAttr(GoConstant.USER_SESSION_KEY);
			if(logger.isInfoEnabled()){
				logger.info("断开连接用户：{}-{}", user.getId(),session);
			}
		}
		
		if(logger.isInfoEnabled()){
			logger.info("有连接关闭！ 当前在线人数：{},s={},u={}", onlineNumber,sessions.size(),sessionMap.size());
		}
	}
	
	public static void addUser(Long uid,MySocketSession session){
		if(logger.isInfoEnabled()){
			logger.info("登录用户：{}-{}", uid,session);
			logger.info("当前在线人数{},s={},u={}", onlineNumber,sessions.size(),sessionMap.size());
		}
		sessionMap.put(uid, session);
	}

	public static GameUser getUser(Long uid) {
		MySocketSession session = getSession(uid);
		if(session != null) {
			return session.getUser();
		}
		return null;
	}
	
	public static MySocketSession getSession(long id){
		return sessionMap.get(id);
	}
	
	public static Collection<MySocketSession> getUserSessions(){
		return sessionMap.values();
	}

	private static Map<Integer,Room> rooms = Maps.newConcurrentMap();
	
	public static Room getRoom(Integer roomId) {
		Room room = rooms.get(roomId);
		if(room == null){
			room = new Room(roomId);
			UsrGroups group = getUsrGroup(roomId.longValue());
			if(group != null) {
				room.setGroups(group);
			}
			rooms.put(room.getId(),room);
		}
		return room;
	}
	public static Collection<Room> getRooms() {
		return rooms.values();
	}
	
	/**
	 * 获取路人房间
	 * @return
	 */
	private static List<Room> norRooms = Lists.newArrayList();;
	public static List<Room> getNorRooms(){
		return norRooms;
	}
	public static void initNorRooms(int type) {
		String[] rc1 = GameConf.getConfStr("room_coin_"+type).split(",");;
		for(int i=0;i<rc1.length;i++){
			String[] rcs = rc1[i].split("-");
			int id = GoConstant.LRROOM_ID_START*type+i;
			Room room = new Room(id,Integer.parseInt(rcs[0]),Integer.parseInt(rcs[1]));
			room.setType(type);
			if(type == GoConstant.GAME_TYPE_S) {
				room.setRate(GameConf.leiReward[i*3]/10.0);
				room.setNum(7+i);
			}else if(type == GoConstant.GAME_TYPE_J){
				room.setNum(5+i);
			}else if(type == GoConstant.GAME_TYPE_F){
				room.setNum(100);
			}
			norRooms.add(room);
			rooms.put(room.getId(),room);
			
			if(type != GoConstant.GAME_TYPE_F) {
				room.initRobot();
			}
			
		}
	}
	
	
	private static Map<Long,UsrGroups> groups;
	public static Collection<UsrGroups> getGroups(){
		if(groups == null){
			groups = Maps.newHashMap();
			List<UsrGroups> groups_ = DaoUtils.getList(UsrGroups.class);
			groups_.forEach((it)->{
				groups.put(it.getId(),it);
			});
		}
		return groups.values();
	}
	
	public static void addGroup(UsrGroups group){
		groups.put(group.getId(),group);
	}
	
	public static UsrGroups getUsrGroup(Long gid) {
		return groups.get(gid);
	}

	private static Map<Integer,QhbGame> games = Maps.newConcurrentMap();
	public static void addGame(QhbGame game) {
		games.put(game.getId(), game);
	}
	public static QhbGame getGame(int gid){
		return games.get(gid);
	}
	
	public static Set<Long> currFlUids = Sets.newHashSet();
	
	/**
	 * 清理游戏信息
	 */
	public static void clearGames() {
		logger.error("开始清理过期游戏...");
		Long now = System.currentTimeMillis()/1000;
		int expire = 3600*24;
		for(QhbGame game:games.values()) {
			if(game.getCreatTime() < now - expire) {
				games.remove(game.getId());
			}
		}
		logger.error("清理过期游戏完成！");
	}

	
}
